//
//  AddScheduleViewController.m
//  TestAfn2
//
//  Created by xujingjing on 16/7/11.
//  Copyright © 2016年 xujingjing. All rights reserved.
//


#define CHOSE_PHOTO_NUM 10
#define Lon 4
#define ImageH (SCREEN_WIDTH-50)/4
#define SomeSize CGSizeMake(SCREEN_WIDTH, SCREEN_HEIGHT)

#define SPACE 10


#import "NewAlbunVC.h"

#import "UzysAssetsPickerController.h"

#import <MobileCoreServices/MobileCoreServices.h>
#import <AVFoundation/AVFoundation.h>
#import <AssetsLibrary/ALAsset.h>
#import <AssetsLibrary/ALAssetsLibrary.h>
#import <AssetsLibrary/ALAssetsGroup.h>
#import <AssetsLibrary/ALAssetRepresentation.h>



@interface NewAlbunVC ()<UzysAssetsPickerControllerDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>{
    
    NSMutableArray *_imagefromSArr;//存放从服务器取得的图片url数组
    NSMutableArray *_imageIdfromSArr;//存放从服务器取得的图片id数组
    
}

@property (weak, nonatomic) IBOutlet UIButton *addImageBtn;  //添加按钮
@property (weak, nonatomic) IBOutlet UILabel *helpL;  //提示可选相片张数
@property (weak, nonatomic) IBOutlet UIView *btnView;


@property(nonatomic,strong)NSMutableArray *images;//图片
@property(nonatomic,assign) int i;
@property(nonatomic,assign) long j;
@property(nonatomic,strong)NSMutableArray *imagesURL;//存储要上传的图片本地路径
@property(nonatomic,strong) NSMutableArray *imageNames;  //存储要上传的图片名称


//添加按钮的约束
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *addBtnX;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *AddbtnY;

@end

@implementation NewAlbunVC

{
    UIView *botView;
    
    CGFloat height_y;//添加按钮的高度
}
//选择完的图片加入图片数组，显示出来
- (void)UzysAssetsPickerController:(UzysAssetsPickerController *)picker didFinishPickingAssets:(NSArray *)assets
{
    NSString * assetPropertyType = (NSString *)[assets[0] valueForProperty:@"ALAssetPropertyType"];
    if([assetPropertyType isEqualToString:@"ALAssetTypePhoto"]) //Photo
    {
        [assets enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
            ALAsset *representation = obj;
            UIImage *img = [UIImage imageWithCGImage:representation.defaultRepresentation.fullScreenImage
                            ];
          
            [self.images addObject:img];
            [self showImages];
          
        
            
            NSArray* paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
          
            self.i++;
            NSString *fileName = [NSString stringWithFormat:@"mainTanceee%d.jpg",self.i];
            NSString *filePath = [[paths objectAtIndex:0] stringByAppendingString:fileName];
            [UIImageJPEGRepresentation([ALTools imageWithImage:img], 0.9) writeToFile:filePath atomically:YES];
            [self.imagesURL addObject:filePath];
            [self.imageNames addObject:fileName];
            
            
            
        }];
         }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.j=10000;
    
    _helpL.text = [NSString stringWithFormat:@"相册最多可上传%d张",CHOSE_PHOTO_NUM];
    
   
    
}


#pragma mark - ImagePickerControllerDelegate

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    UIImage *imageNew = info[@"UIImagePickerControllerEditedImage"];
    
    [_images addObject:imageNew];
    
    [self showImages];
    
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (IBAction)pickImageAction:(id)sender {

    if (self.images.count >= CHOSE_PHOTO_NUM -_imageIdfromSArr.count ) {
    //    [FAlertView showMsg:[NSString stringWithFormat:@"最多上传%d张照片哦！", CHOSE_PHOTO_NUM] cancelDelay:1];
        //        SHOWMESSEGE(@"最多上传3张照片哦！");
        [ALTools ttAlert:(@"最多上传3张照片哦！")];
        return;
    }
    UIAlertController *alertC = [UIAlertController alertControllerWithTitle:@"上传照片" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    __weak typeof(self) weakSelt = self;
    UIAlertAction *albumAction = [UIAlertAction actionWithTitle:@"相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        [weakSelt chooseImageFromAlbum];
    }];
    UIAlertAction *takePhotoAction = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        [weakSelt takePhoto];
    }];
    [alertC addAction:cancelAction];
    [alertC addAction:albumAction];
    [alertC addAction:takePhotoAction];
    [self presentViewController:alertC animated:YES completion:nil];
    
}


-(void)chooseImageFromAlbum
{
    
    UzysAssetsPickerController *picker = [[UzysAssetsPickerController alloc] init];
    picker.didSelectedPhotoNumber = _images.count+_imageIdfromSArr.count;
    picker.maximumNumberOfSelectionPhoto = CHOSE_PHOTO_NUM;
    picker.delegate = self;
    
    [self  presentViewController:picker animated:YES completion:nil];
}



-(void)takePhoto
{
    NSString *mediaType = AVMediaTypeVideo;
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:mediaType];
    if(authStatus == ALAuthorizationStatusRestricted || authStatus == ALAuthorizationStatusDenied){
        
        [ALTools ttAlert:@"请到设置中打开心相机权限"];
        return;
    }
    
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        UIImagePickerController *controller = [[UIImagePickerController alloc] init];
        [controller setSourceType:UIImagePickerControllerSourceTypeCamera];// 设置类型
        
        controller.delegate = self;
        controller.allowsEditing = YES;
        
        if([[[UIDevice currentDevice] systemVersion] floatValue]>=8.0) {
            
            self.modalPresentationStyle=UIModalPresentationOverCurrentContext;
            
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [self presentViewController:controller animated:YES completion:^{
                
            }];
        });
    }else{
        [ALTools ttAlert:@"这台设备没有相机"];
    }
}


//显示图片
-(void)showImages{
    
    if (self.btnView.subviews.count>0) {
        
        for (UIView *iv in self.btnView.subviews) {
            if ([iv isMemberOfClass:[UIButton class]]) {
                continue;//是添加按钮，不删除
            }
            [iv removeFromSuperview];
        }
        
    }
    if (self.images.count==0) {

      return;
    }
    
    CGFloat startX = 0;
    CGRect frame = CGRectMake(startX, 10, ImageH, ImageH);
    
    for (int i = 0; i < self.images.count; i++) {
        UIImageView *iv = [[UIImageView alloc]init];
        iv.contentMode = UIViewContentModeScaleToFill;
        iv.frame = frame;
        iv.image = self.images[i];
        iv.userInteractionEnabled =YES;
        frame.origin.x = frame.origin.x + frame.size.width + SPACE;
        
        if (frame.origin.x> (SCREEN_WIDTH-ImageH)) {
            frame.origin.x = startX;
            
            frame.origin.y = frame.origin.y+ImageH + SPACE;
        }
        
        [self.btnView addSubview:iv];
        
        UIButton *deleteBtn = [[UIButton alloc]initWithFrame:CGRectMake(ImageH-30, -15, 44, 44)];
        //deleteBtn.backgroundColor = [UIColor greenColor];
        [deleteBtn setImage:[UIImage imageNamed:@"游记_发布_03"] forState:UIControlStateNormal];
        deleteBtn.imageEdgeInsets = UIEdgeInsetsMake(11, 11, 11, 11);
        
        [deleteBtn addTarget:self action:@selector(deleteImage:) forControlEvents:UIControlEventTouchDown];
        deleteBtn.tag = i;//标记， 删除用
        deleteBtn.userInteractionEnabled = YES;
        [iv addSubview:deleteBtn];
        
        if ((int)self.images.count-1 == i) {//把添加按钮防灾图片最后
            CGRect fra = _addImageBtn.frame;
            fra.origin.x = frame.origin.x;
            fra.origin.y = frame.origin.y;
            _addImageBtn.frame = fra;

            _addBtnX.constant = frame.origin.x;
            _AddbtnY.constant = fra.origin.y;
        }
    }
}

//删除图片
-(void)deleteImage:(UIButton *)btn{
    
    if (self.images.count==0) {
        return;
    }
    //删除掉
    [self.images removeObjectAtIndex:btn.tag];
//    [self.imagesURL removeObjectAtIndex:btn.tag];
//    [self.imageNames removeObjectAtIndex:btn.tag];
    [self showImages];
}



- (IBAction)saveAction:(id)sender {
 //   [self showHint:@"正在保存"];
    
    NSString *imageParam;
    imageParam = @"";
    for (NSString *imageName in self.imageNames) {

        imageParam = [NSString stringWithFormat:@"%@%@,",imageParam,imageName];
    }
    if (self.imageNames.count>0) {
        imageParam = [imageParam substringToIndex:imageParam.length - 1];
    }
    NSLog(@"imageParam=%@,_imageNames=%@,_imagesURL=%@,_images=%@",imageParam,_imageNames,_imagesURL,_images);
    
    NSMutableArray *imageNameArr = [NSMutableArray array];
    for (int i = 0; i<_images.count; i++) {
        NSData *newdata=  [ALTools dataWithImage:_images[i]];
        NSArray* newpaths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
        NSString *newfileName = @"mainTance.png";
        
        [newdata writeToFile:[[newpaths objectAtIndex:0] stringByAppendingString:newfileName] atomically:YES];
        
        
        [imageNameArr addObject:newdata];
    }
    
    NSMutableArray *imagePathArr = [NSMutableArray array];
    for (int i = 0; i<_images.count; i++) {
        [imagePathArr addObject:[NSString stringWithFormat:@"fileName%d",i]];
    }
    
    
    [self popAction];
    
}

-(void)popAction
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

#pragma marksetter and getter
-(NSMutableArray *)imagesURL
{
    if (!_imagesURL) {
        _imagesURL = [[NSMutableArray alloc]init];
    }
    return _imagesURL;
}

-(NSMutableArray *)imageNames
{
    if (!_imageNames) {
        _imageNames = [[NSMutableArray alloc]init];
    }
    return _imageNames;
}



-(NSMutableArray *)images{
    if (!_images) {
        _images = [[NSMutableArray alloc]init];
    }
    return _images;
}

@end
